<?php
// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 检查数据库表状态
global $wpdb;
$stats_table = $wpdb->prefix . 'spider_stats';
$visits_table = $wpdb->prefix . 'spider_visits';

$visits_exists = $wpdb->get_var("SHOW TABLES LIKE '$visits_table'") == $visits_table;
$stats_exists = $wpdb->get_var("SHOW TABLES LIKE '$stats_table'") == $stats_table;
$tables_exist = $visits_exists && $stats_exists;

// 如果表不存在，尝试自动创建
if (!$tables_exist) {
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql1 = "CREATE TABLE $visits_table (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        spider_name varchar(100) NOT NULL,
        user_agent text NOT NULL,
        ip_address varchar(45) NOT NULL,
        url varchar(500) NOT NULL,
        referer varchar(500),
        visit_time datetime DEFAULT CURRENT_TIMESTAMP,
        response_code int(3) DEFAULT 200,
        response_time decimal(10,3),
        page_title varchar(255),
        PRIMARY KEY (id),
        KEY spider_name (spider_name),
        KEY visit_time (visit_time),
        KEY url (url(191))
    ) $charset_collate;";
    
    $sql2 = "CREATE TABLE $stats_table (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        spider_name varchar(100) NOT NULL,
        visit_date date NOT NULL,
        visit_count int(11) DEFAULT 0,
        unique_pages int(11) DEFAULT 0,
        total_response_time decimal(10,3) DEFAULT 0,
        avg_response_time decimal(10,3) DEFAULT 0,
        last_visit datetime,
        PRIMARY KEY (id),
        UNIQUE KEY spider_date (spider_name, visit_date)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql1);
    dbDelta($sql2);
    
    $visits_exists = $wpdb->get_var("SHOW TABLES LIKE '$visits_table'") == $visits_table;
    $stats_exists = $wpdb->get_var("SHOW TABLES LIKE '$stats_table'") == $stats_table;
    $tables_exist = $visits_exists && $stats_exists;
    
    if ($tables_exist) {
        update_option('wp_spider_monitor_tables_created', true);
    }
}

// 获取今日统计数据
// 统一使用 spider_visits 表 + 北京时区窗口，保证与趋势图一致
$today = null; $today_start = null; $today_end = null;
try {
    $tz = new \DateTimeZone('Asia/Shanghai');
    $nowCn = new \DateTimeImmutable('now', $tz);
    $today = $nowCn->format('Y-m-d');
    $today_start = $nowCn->setTime(0,0,0)->format('Y-m-d H:i:s');
    $today_end   = $nowCn->setTime(23,59,59)->format('Y-m-d H:i:s');
} catch (\Exception $e) {
    $today = current_time('Y-m-d');
    $today_start = $today . ' 00:00:00';
    $today_end   = $today . ' 23:59:59';
}

$total_visits = 0;
$total_spiders = 0;
$total_pages = 0;

if ($tables_exist) {
    $visits_table = $wpdb->prefix . 'spider_visits';
    // 今日总访问
    $total_visits = intval($wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $visits_table WHERE visit_time BETWEEN %s AND %s",
        $today_start, $today_end
    )) ?: 0);
    // 活跃蜘蛛数（去重）
    $total_spiders = intval($wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(DISTINCT spider_name) FROM $visits_table WHERE visit_time BETWEEN %s AND %s",
        $today_start, $today_end
    )) ?: 0);
    // 爬取页面数（去重）
    $total_pages = intval($wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(DISTINCT url) FROM $visits_table WHERE visit_time BETWEEN %s AND %s",
        $today_start, $today_end
    )) ?: 0);
}

// 获取热门路径数据
$popular_paths = array();
if ($tables_exist) {
    $popular_paths = $wpdb->get_results($wpdb->prepare("
        SELECT 
            SUBSTRING_INDEX(url, '?', 1) as path,
            COUNT(*) as visit_count
        FROM {$wpdb->prefix}spider_visits 
        WHERE DATE(visit_time) = %s
        GROUP BY path
        ORDER BY visit_count DESC
        LIMIT 5
    ", $today));
}

// 获取状态码统计
$status_codes = array();
if ($tables_exist) {
    $status_codes = $wpdb->get_results($wpdb->prepare("
        SELECT 
            response_code,
            COUNT(*) as count
        FROM {$wpdb->prefix}spider_visits 
        WHERE DATE(visit_time) = %s
        GROUP BY response_code
        ORDER BY count DESC
        LIMIT 5
    ", $today));
}

// 获取最近访问记录
$recent_visits = array();
if ($tables_exist) {
    $recent_visits = $wpdb->get_results("
        SELECT spider_name, url, visit_time, response_code
        FROM {$wpdb->prefix}spider_visits
        ORDER BY visit_time DESC
        LIMIT 10
    ");
}

// 获取蜘蛛列表
$spider_list = array();
if ($tables_exist) {
    $spider_list = $wpdb->get_results("
        SELECT DISTINCT spider_name, COUNT(*) as total_visits,
               MAX(visit_time) as last_visit
        FROM {$wpdb->prefix}spider_visits
        GROUP BY spider_name
        ORDER BY total_visits DESC
    ");
}
?>

<div class="wrap spider-monitor-wrap">
    <!-- WordPress标准头部 -->
    <h1 class="wp-heading-inline">
        <span class="dashicons dashicons-chart-line"></span>
        蜘蛛监控中心
    </h1>
    <a href="<?php echo admin_url('admin.php?page=wp-spider-monitor-settings'); ?>" class="page-title-action">
        <span class="dashicons dashicons-admin-generic"></span>
        设置
    </a>
    
    <hr class="wp-header-end">

    <!-- 数据库状态提示 -->
    <?php if (!$tables_exist): ?>
        <div class="notice notice-error">
            <p><strong>⚠️ 数据库表不存在</strong> - 请点击下方按钮创建必要的数据表。</p>
            <p>
                <button id="create-tables-btn" class="button button-primary">
                    <span class="dashicons dashicons-database-add"></span>
                    创建数据表
                </button>
            </p>
        </div>
    <?php else: ?>
        <div class="notice notice-success is-dismissible">
            <p><strong>✅ 系统运行正常</strong> - 正在实时监控蜘蛛访问。</p>
        </div>
    <?php endif; ?>

    <!-- 顶部统计卡片 -->
    <div class="spider-stats-cards">
        <div class="stats-card stats-card-primary">
            <div class="stats-card-icon">
                <span class="dashicons dashicons-chart-bar"></span>
            </div>
            <div class="stats-card-content">
                <h3><?php echo number_format($total_visits); ?></h3>
                <p>今日总访问</p>
            </div>
        </div>

        <div class="stats-card stats-card-success">
            <div class="stats-card-icon">
                <span class="dashicons dashicons-smiley"></span>
            </div>
            <div class="stats-card-content">
                <h3><?php echo $total_spiders; ?></h3>
                <p>活跃蜘蛛数</p>
            </div>
        </div>

        <div class="stats-card stats-card-info">
            <div class="stats-card-icon">
                <span class="dashicons dashicons-admin-links"></span>
            </div>
            <div class="stats-card-content">
                <h3><?php echo number_format($total_pages); ?></h3>
                <p>爬取页面数</p>
            </div>
        </div>

        <div class="stats-card stats-card-warning">
            <div class="stats-card-icon">
                <span class="dashicons dashicons-clock"></span>
            </div>
            <div class="stats-card-content">
                <h3>--</h3>
                <p>平均响应时间</p>
            </div>
        </div>
    </div>

    <!-- 主要内容网格 -->
    <div class="spider-dashboard-grid">
        <!-- 图表和内容区域 -->
        <div class="dashboard-content">
            <!-- 图表网格 -->
            <div class="charts-grid">
                <!-- 蜘蛛访问趋势图表 -->
                <div class="postbox chart-card">
                    <div class="postbox-header">
                        <h2 class="hndle">
                            <span class="dashicons dashicons-chart-area"></span>
                            蜘蛛访问趋势
                        </h2>
                        <div class="handle-actions">
                            <button type="button" class="handlediv" aria-expanded="true">
                                <span class="screen-reader-text">切换面板</span>
                                <span class="toggle-indicator" aria-hidden="true"></span>
                            </button>
                        </div>
                    </div>
                    <div class="inside chart-body">
                        <canvas id="spider-trend-chart" height="200"></canvas>
                    </div>
                </div>

                <!-- 错误状态统计图表 -->
                <div class="postbox chart-card">
                    <div class="postbox-header">
                        <h2 class="hndle">
                            <span class="dashicons dashicons-shield"></span>
                            错误状态分析
                        </h2>
                    </div>
                    <div class="inside chart-body">
                        <canvas id="spider-error-chart" height="200"></canvas>
                    </div>
                </div>

                <!-- 蜘蛛活动排行图表 -->
                <div class="postbox chart-card">
                    <div class="postbox-header">
                        <h2 class="hndle">
                            <span class="dashicons dashicons-chart-bar"></span>
                            蜘蛛活动排行
                        </h2>
                        <div class="handle-actions">
                            <button type="button" class="handlediv" aria-expanded="true">
                                <span class="screen-reader-text">切换面板</span>
                                <span class="toggle-indicator" aria-hidden="true"></span>
                            </button>
                        </div>
                    </div>
                    <div class="inside chart-body">
                        <canvas id="spider-activity-chart" height="200"></canvas>
                    </div>
                </div>

                <!-- 访问路径分布图表 -->
                <div class="postbox chart-card">
                    <div class="postbox-header">
                        <h2 class="hndle">
                            <span class="dashicons dashicons-chart-pie"></span>
                            访问路径分布
                        </h2>
                        <div class="handle-actions">
                            <button type="button" class="handlediv" aria-expanded="true">
                                <span class="screen-reader-text">切换面板</span>
                                <span class="toggle-indicator" aria-hidden="true"></span>
                            </button>
                        </div>
                    </div>
                    <div class="inside chart-body">
                        <canvas id="paths-pie-chart" height="200"></canvas>
                    </div>
                </div>

                <!-- 24小时蜘蛛热力图（高级） -->
                <div class="postbox chart-card">
                    <div class="postbox-header">
                        <h2 class="hndle">
                            <span class="dashicons dashicons-visibility"></span>
                            24小时蜘蛛热力图（高级）
                        </h2>
                    </div>
                    <div class="inside chart-body pro-container<?php echo (!function_exists('wp_spider_is_premium') || !wp_spider_is_premium()) ? ' locked' : ''; ?>">
                        <canvas id="spider-heatmap" height="200"></canvas>
                        <?php if (!function_exists('wp_spider_is_premium') || !wp_spider_is_premium()): ?>
                            <div class="pro-overlay" id="overlay-heatmap">
                                <a class="pro-btn" href="https://zibovip.top/spider-monitor-pricing" target="_blank" rel="noopener">获取PRO版本</a>
                                <div class="pro-note">* 激活PRO版本即可加载</div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- 蜘蛛来源占比（高级） -->
                <div class="postbox chart-card">
                    <div class="postbox-header">
                        <h2 class="hndle">
                            <span class="dashicons dashicons-chart-pie"></span>
                            蜘蛛来源占比（高级）
                        </h2>
                    </div>
                    <div class="inside chart-body pro-container<?php echo (!function_exists('wp_spider_is_premium') || !wp_spider_is_premium()) ? ' locked' : ''; ?>">
                        <canvas id="spider-sources-premium" height="200"></canvas>
                        <?php if (!function_exists('wp_spider_is_premium') || !wp_spider_is_premium()): ?>
                            <div class="pro-overlay" id="overlay-sources">
                                <a class="pro-btn" href="https://zibovip.top/spider-monitor-pricing" target="_blank" rel="noopener">获取PRO版本</a>
                                <div class="pro-note">* 激活PRO版本即可加载</div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- 其他内容网格 -->
            <div class="other-content-grid">
                <!-- 热门路径 -->
                <div class="postbox">
                    <div class="postbox-header">
                        <h2 class="hndle">
                            <span class="dashicons dashicons-admin-links"></span>
                            热门路径
                        </h2>
                    </div>
                    <div class="inside">
                        <?php if (empty($popular_paths)): ?>
                            <p class="no-data">暂无数据</p>
                        <?php else: ?>
                            <ul class="popular-paths-list">
                                <?php foreach ($popular_paths as $path): ?>
                                    <li>
                                        <span class="path-url" title="<?php echo esc_attr($path->path); ?>">
                                            <?php echo esc_html(strlen($path->path) > 30 ? substr($path->path, 0, 30) . '...' : $path->path); ?>
                                        </span>
                                        <span class="path-count"><?php echo number_format($path->visit_count); ?></span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- 状态码统计 -->
                <div class="postbox">
                    <div class="postbox-header">
                        <h2 class="hndle">
                            <span class="dashicons dashicons-warning"></span>
                            状态码统计
                        </h2>
                    </div>
                    <div class="inside">
                        <?php if (empty($status_codes)): ?>
                            <p class="no-data">暂无数据</p>
                        <?php else: ?>
                            <ul class="status-codes-list">
                                <?php foreach ($status_codes as $status): ?>
                                    <li>
                                        <span class="status-badge status-<?php echo $status->response_code; ?>">
                                            <?php echo $status->response_code; ?>
                                        </span>
                                        <span class="status-count"><?php echo number_format($status->count); ?></span>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- 快速操作 -->
                <div class="postbox">
                    <div class="postbox-header">
                        <h2 class="hndle">
                            <span class="dashicons dashicons-admin-tools"></span>
                            快速操作
                        </h2>
                    </div>
                    <div class="inside">
                        <div class="quick-actions">
                            <a href="<?php echo admin_url('admin.php?page=wp-spider-monitor-details'); ?>" 
                               class="button button-primary button-large" style="width: 100%; margin-bottom: 5px;">
                                <span class="dashicons dashicons-search"></span>
                                查看详情
                            </a>
                            <button class="button button-secondary" style="width: 100%; margin-bottom: 5px;" 
                                    onclick="exportData()">
                                <span class="dashicons dashicons-download"></span>
                                导出数据
                            </button>
                            <button class="button button-secondary" style="width: 100%;" 
                                    onclick="clearData()">
                                <span class="dashicons dashicons-trash"></span>
                                清理数据
                            </button>
                            <button class="button button-primary" style="width: 100%; margin-top: 10px;" 
                                    onclick="testInsert()">
                                <span class="dashicons dashicons-admin-tools"></span>
                                测试插入
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 蜘蛛列表 -->
            <div class="postbox">
                <div class="postbox-header">
                    <h2 class="hndle">
                        <span class="dashicons dashicons-list-view"></span>
                        蜘蛛列表
                    </h2>
                </div>
                <div class="inside">
                    <?php if (empty($spider_list)): ?>
                        <p class="no-data">暂无蜘蛛访问记录</p>
                    <?php else: ?>
                        <table class="wp-list-table widefat fixed striped">
                            <thead>
                                <tr>
                                    <th>蜘蛛名称</th>
                                    <th>总访问次数</th>
                                    <th>最后访问时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($spider_list as $spider): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo esc_html($spider->spider_name); ?></strong>
                                        </td>
                                        <td><?php echo number_format($spider->total_visits); ?></td>
                                        <td><?php echo date('Y-m-d H:i', strtotime($spider->last_visit)); ?></td>
                                        <td>
                                            <a href="<?php echo admin_url('admin.php?page=wp-spider-monitor-details&spider=' . urlencode($spider->spider_name)); ?>" 
                                               class="button button-small">
                                                查看详情
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>

            <!-- 最近访问记录 -->
            <div class="postbox">
                <div class="postbox-header">
                    <h2 class="hndle">
                        <span class="dashicons dashicons-clock"></span>
                        最近访问记录
                    </h2>
                </div>
                <div class="inside">
                    <?php if (empty($recent_visits)): ?>
                        <p class="no-data">暂无访问记录</p>
                    <?php else: ?>
                        <table class="wp-list-table widefat fixed striped">
                            <thead>
                                <tr>
                                    <th>时间</th>
                                    <th>蜘蛛</th>
                                    <th>URL</th>
                                    <th>状态码</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recent_visits as $visit): ?>
                                    <tr>
                                        <td><?php echo date('H:i', strtotime($visit->visit_time)); ?></td>
                                        <td><?php echo esc_html($visit->spider_name); ?></td>
                                        <td>
                                            <span class="url-cell" title="<?php echo esc_attr($visit->url); ?>">
                                                <?php echo esc_html(strlen($visit->url) > 50 ? substr($visit->url, 0, 50) . '...' : $visit->url); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="status-code status-<?php echo $visit->response_code; ?>">
                                                <?php echo $visit->response_code; ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
// 确保Chart.js被加载
wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js', array(), '3.9.1', true);
?>

<style>
/* WordPress后台专用样式 */
.spider-monitor-wrap {
    max-width: 100%;
    margin: 0;
}

.spider-stats-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
    margin: 10px 0;
}

.stats-card {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-left: 4px solid #0073aa;
    padding: 10px;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
    border-radius: 0;
    display: flex;
    align-items: center;
}

.stats-card-primary { border-left-color: #0073aa; }
.stats-card-success { border-left-color: #46b450; }
.stats-card-info { border-left-color: #00a0d2; }
.stats-card-warning { border-left-color: #ffb900; }

.stats-card-icon {
    font-size: 20px;
    color: #8c8f94;
    margin-left: 10px;
}

.stats-card-content h3 {
    margin: 0;
    font-size: 28px;
    font-weight: 400;
    line-height: 1.2;
    color: #1d2327;
}

.stats-card-content p {
    margin: 5px 0 0;
    color: #50575e;
    font-size: 13px;
}

.spider-dashboard-grid {
    display: block;
    margin-top: 10px;
}

.dashboard-content {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.charts-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
}

.other-content-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10px;
    margin-top: 10px;
}

.chart-card {
    margin: 0;
}

.chart-card .chart-body {
    height: 200px;
    padding: 5px;
}

.pro-container { position: relative; }
.pro-overlay {
    position: absolute; inset: 0;
    display: flex; align-items: center; justify-content: center;
    background: rgba(0,0,0,0.55);
    color: #fff; font-weight: 600; font-size: 16px;
    opacity: 0; transition: opacity .2s ease-in-out;
    pointer-events: none;
    flex-direction: column; gap: 8px;
}

.pro-container:hover .pro-overlay { opacity: 1; }
.pro-container.locked .pro-overlay { opacity: 1; pointer-events: auto; }
.pro-container.locked canvas { display: none; }
.pro-btn {
    background: #4F8FF7;
    color: #fff; padding: 8px 14px; border-radius: 6px; text-decoration: none;
    pointer-events: auto; /* 允许点击 */
}
.pro-btn:hover { background: #2e6fe1; }
.pro-note { font-size: 12px; opacity: .9; }

.postbox {
    margin: 0;
    border-radius: 0;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
}

.postbox-header {
    padding: 5px 10px;
}

.postbox .inside {
    padding: 10px;
    margin: 0;
}

.no-data {
    text-align: center;
    color: #8c8f94;
    font-style: italic;
    padding: 10px;
}

.popular-paths-list,
.status-codes-list {
    margin: 0;
    padding: 0;
    list-style: none;
}

.popular-paths-list li,
.status-codes-list li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 5px 0;
    border-bottom: 1px solid #f0f0f1;
}

.popular-paths-list li:last-child,
.status-codes-list li:last-child {
    border-bottom: none;
}

.path-url,
.status-badge {
    font-family: monospace;
    font-size: 12px;
}

.status-badge {
    padding: 2px 6px;
    border-radius: 3px;
    color: #fff;
    font-weight: bold;
}

.status-200 { background-color: #46b450; }
.status-404 { background-color: #dc3232; }
.status-500 { background-color: #d63638; }
.status-301 { background-color: #ffb900; }
.status-302 { background-color: #f56e28; }

.url-cell {
    font-family: monospace;
    font-size: 12px;
    color: #50575e;
}

@media screen and (max-width: 782px) {
    .charts-grid { grid-template-columns: 1fr; }
    .other-content-grid { grid-template-columns: 1fr; }
    .spider-stats-cards { grid-template-columns: 1fr; }
}
</style>

<script>
jQuery(document).ready(function($) {
    // 创建数据表
    $('#create-tables-btn').on('click', function() {
        var button = $(this);
        button.prop('disabled', true).text('创建中...');
        
        $.ajax({
            url: wpSpiderMonitor.ajax_url,
            type: 'POST',
            data: {
                action: 'create_spider_tables',
                nonce: wpSpiderMonitor.nonce
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert('创建失败：' + response.data);
                    button.prop('disabled', false).html('<span class="dashicons dashicons-database-add"></span> 创建数据表');
                }
            }
        });
    });

    // 导出数据
    window.exportData = function() {
        window.location.href = wpSpiderMonitor.ajax_url + '?action=export_spider_data&nonce=' + wpSpiderMonitor.nonce;
    };

    // 清理数据
    window.clearData = function() {
        if (confirm('确定要清理所有蜘蛛访问数据吗？此操作不可恢复！')) {
            $.ajax({
                url: wpSpiderMonitor.ajax_url,
                type: 'POST',
                data: {
                    action: 'clear_spider_data',
                    nonce: wpSpiderMonitor.nonce
                },
                success: function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('清理失败：' + response.data);
                    }
                }
            });
        }
    };

    // 测试插入
    window.testInsert = function() {
        $.ajax({
            url: wpSpiderMonitor.ajax_url,
            type: 'POST',
            data: {
                action: 'test_insert',
                nonce: wpSpiderMonitor.nonce
            },
            success: function(response) {
                if (response.success) {
                    alert('测试插入成功: ' + response.data);
                    // 刷新页面数据
                    loadDailyStats();
                } else {
                    alert('测试插入失败: ' + response.data);
                }
            },
            error: function() {
                alert('测试插入失败，请重试');
            }
        });
    };

    // 加载图表数据
    function loadSpiderChartData() {
        if (typeof Chart === 'undefined') {
            console.error('Chart.js 未加载');
            return;
        }

        // 获取蜘蛛访问趋势数据（也用于构建活动排行）
        $.post(wpSpiderMonitor.ajax_url, {
            action: 'spider_get_daily_stats',
            nonce: wpSpiderMonitor.nonce,
            days: 7
        })
        .done(function(response) {
            if (response.success && response.data) {
                initSpiderTrendChart(response.data);
                initSpiderActivityChart(response.data);
            }
        })
        .fail(function() {
            console.error('加载图表数据失败');
        });

        // 错误状态统计
        $.post(wpSpiderMonitor.ajax_url, {
            action: 'spider_error_stats',
            nonce: wpSpiderMonitor.nonce
        }).done(function(resp){
            initSpiderErrorChart(resp && resp.success ? (resp.data || []) : []);
        }).fail(function(){
            initSpiderErrorChart([]);
        });

        // 仅在已激活情况下尝试加载高级图表；未激活则不渲染（保持遮罩）
        var isPremium = !!(window.wpSpiderMonitor && wpSpiderMonitor.subscription && wpSpiderMonitor.subscription.is_premium);

        if (isPremium) {
            $.post(wpSpiderMonitor.ajax_url, {
                action: 'spider_heatmap_24h',
                nonce: wpSpiderMonitor.nonce
            }).done(function(resp){
                initSpiderHeatmap(resp && resp.success ? (resp.data || []) : []);
            }).fail(function(){ initSpiderHeatmap([]); });

            $.post(wpSpiderMonitor.ajax_url, {
                action: 'spider_sources_premium',
                nonce: wpSpiderMonitor.nonce
            }).done(function(resp){
                initSpiderSourcesChart(resp && resp.success ? (resp.data || []) : []);
            }).fail(function(){ initSpiderSourcesChart([]); });
        } else {
            // 未激活：不渲染
        }

        // 路径分布（当前无后端接口，渲染空基线）
        initPathsPieChart([]);
    }

    // 初始化蜘蛛趋势图表
    function initSpiderTrendChart(data) {
        const canvas = document.getElementById('spider-trend-chart');
        if (!canvas) {
            console.log('蜘蛛趋势图表canvas未找到');
            return;
        }

        try {
            const ctx = canvas.getContext('2d');
            if (!ctx) {
                console.error('无法获取2D上下文');
                return;
            }

            if (!data || !data.hourly_stats) {
                console.log('没有可用的图表数据');
                return;
            }

            // 分别取今天与昨日数据
            const todayStats = data.hourly_stats || {};
            const yesterdayStats = data.previous_hourly_stats || {};
            const spiderNames = Array.from(new Set([].concat(Object.keys(todayStats), Object.keys(yesterdayStats))));
            const currentHour = data.current_hour !== undefined ? data.current_hour : new Date().getHours();
            
            // 如果今天和昨天的数据都为空，渲染一条零值基线，避免空白
            const renderEmptyBaseline = (spiderNames.length === 0);

            // 准备图表数据 - 只显示到当前小时
            const labels = [];
            for (let hour = 0; hour <= currentHour; hour++) {
                labels.push(`${hour.toString().padStart(2, '0')}:00`);
            }

            // 定义颜色
            const colors = [
                '#3b82f6', '#ef4444', '#10b981', '#f59e0b', 
                '#8b5cf6', '#06b6d4', '#84cc16', '#f97316'
            ];

            // 构建数据集：今天为实线，昨日为虚线；同一蜘蛛使用同色
            let datasets = [];
            spiderNames.forEach((spiderName, index) => {
                const color = colors[index % colors.length];
                const todayDataMap = todayStats[spiderName] || {};
                const yesterdayDataMap = yesterdayStats[spiderName] || {};
                const todaySeries = Array.from({length: currentHour + 1}, (_, hour) => todayDataMap[hour] || 0);
                const yestSeries = Array.from({length: currentHour + 1}, (_, hour) => yesterdayDataMap[hour] || 0);

                if (Object.keys(todayDataMap).length > 0) {
                    datasets.push({
                        label: spiderName,
                        data: todaySeries,
                        borderColor: color,
                        backgroundColor: `${color}20`,
                        borderWidth: 2,
                        fill: false,
                        tension: 0.1,
                        pointBackgroundColor: color,
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 2,
                        pointRadius: 3,
                        borderDash: []
                    });
                }

                if (Object.keys(yesterdayDataMap).length > 0) {
                    datasets.push({
                        label: spiderName + ' (昨日)',
                        data: yestSeries,
                        borderColor: color,
                        backgroundColor: `${color}10`,
                        borderWidth: 2,
                        fill: false,
                        tension: 0.1,
                        pointBackgroundColor: color,
                        pointBorderColor: '#ffffff',
                        pointBorderWidth: 1,
                        pointRadius: 2,
                        borderDash: [6, 4]
                    });
                }
            });

            if (renderEmptyBaseline || datasets.length === 0) {
                const color = '#94a3b8';
                const chartData = Array.from({length: currentHour + 1}, () => 0);
                datasets = [{
                    label: '无数据',
                    data: chartData,
                    borderColor: color,
                    backgroundColor: `${color}20`,
                    borderWidth: 1,
                    fill: false,
                    tension: 0.1,
                    pointRadius: 0
                }];
            }

            // 检查并销毁已存在的图表实例
            if (window.spiderTrendChart && typeof window.spiderTrendChart.destroy === 'function') {
                window.spiderTrendChart.destroy();
                window.spiderTrendChart = null;
            }

            // 确保canvas没有被其他图表占用
            if (Chart.getChart && Chart.getChart(canvas)) {
                Chart.getChart(canvas).destroy();
            }

            // 创建新图表并保存实例引用
            window.spiderTrendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.05)'
                            },
                            ticks: {
                                color: '#64748b',
                                stepSize: 1
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#64748b',
                                maxRotation: 45
                            }
                        }
                    }
                }
            });
        } catch (error) {
            console.error('创建图表时出错:', error);
        }
    }

    // 蜘蛛活动排行（按今日累计访问数排序，柱状图；没有数据渲染零基线）
    function initSpiderActivityChart(data){
        const canvas = document.getElementById('spider-activity-chart');
        if (!canvas) return;
        try {
            const ctx = canvas.getContext('2d');
            const currentHour = data && (data.current_hour !== undefined) ? data.current_hour : new Date().getHours();
            let hourlyStats = data && data.hourly_stats ? data.hourly_stats : {};
            const spiderNames = Object.keys(hourlyStats || {});
            let labels = [], values = [];
            if (spiderNames.length > 0) {
                labels = spiderNames;
                values = spiderNames.map(name => {
                    const m = hourlyStats[name] || {};
                    let sum = 0; for (let h=0; h<=currentHour; h++){ sum += (m[h] || 0); }
                    return sum;
                });
            } else {
                labels = ['无数据'];
                values = [0];
            }
            if (window.spiderActivityChart && typeof window.spiderActivityChart.destroy==='function') window.spiderActivityChart.destroy();
            window.spiderActivityChart = new Chart(ctx, {
                type: 'bar',
                data: { labels: labels, datasets: [{
                    label: '访问次数',
                    data: values,
                    backgroundColor: '#60a5fa',
                    borderColor: '#3b82f6',
                    borderWidth: 1
                }]},
                options: { responsive:true, maintainAspectRatio:false, scales:{ y:{ beginAtZero:true, ticks:{ stepSize:1 } } } }
            });
        } catch(e){ console.error('初始化活动排行失败', e); }
    }

    // 错误状态统计（没有数据渲染零基线）
    function initSpiderErrorChart(rows){
        const canvas = document.getElementById('spider-error-chart');
        if (!canvas) return;
        try {
            const ctx = canvas.getContext('2d');
            let labels = [], values = [];
            if (rows && rows.length) {
                labels = rows.map(r => r.response_code);
                values = rows.map(r => parseInt(r.count || 0, 10));
            } else { labels = ['无数据']; values = [0]; }
            if (window.spiderErrorChart && typeof window.spiderErrorChart.destroy==='function') window.spiderErrorChart.destroy();
            window.spiderErrorChart = new Chart(ctx, {
                type: 'bar',
                data: { labels: labels, datasets: [{ label: '次数', data: values, backgroundColor:'#34d399', borderColor:'#10b981', borderWidth:1 }]},
                options: { responsive:true, maintainAspectRatio:false, scales:{ y:{ beginAtZero:true, ticks:{ stepSize:1 } } } }
            });
        } catch(e){ console.error('初始化错误状态失败', e); }
    }

    // 访问路径分布（当前无接口：渲染零基线的空饼图）
    function initPathsPieChart(rows){
        const canvas = document.getElementById('paths-pie-chart');
        if (!canvas) return;
        try {
            const ctx = canvas.getContext('2d');
            const labels = ['无数据'];
            const values = [0];
            if (window.pathsPieChart && typeof window.pathsPieChart.destroy==='function') window.pathsPieChart.destroy();
            window.pathsPieChart = new Chart(ctx, {
                type: 'doughnut',
                data: { labels: labels, datasets: [{ data: values, backgroundColor:['#a5b4fc'] }]},
                options: { responsive:true, maintainAspectRatio:false, plugins:{ legend:{ display:true } }, cutout:'70%' }
            });
        } catch(e){ console.error('初始化路径分布失败', e); }
    }

    // 24小时热力图（无数据渲染零基线为 0 的占位折线）
    function initSpiderHeatmap(rows){
        const canvas = document.getElementById('spider-heatmap');
        if (!canvas) return;
        try {
            const ctx = canvas.getContext('2d');
            // 这里用折线图占位显示（真正热力图可后续升级）；无数据显示 0 基线
            const hours = Array.from({length:24}, (_,h)=> (h+''.padStart?String(h).padStart(2,'0'):('0'+h).slice(-2))+':00');
            let datasets = [];
            if (rows && rows.length){
                const bySpider = {};
                rows.forEach(r => { const name = r.spider_name || '未知'; const h = parseInt(r.hour||0,10); const c = parseInt(r.count||0,10); bySpider[name]=bySpider[name]||{}; bySpider[name][h]=c; });
                const colors = ['#f87171','#60a5fa','#34d399','#fbbf24','#a78bfa','#22d3ee','#84cc16','#f97316'];
                Object.keys(bySpider).forEach((name, idx)=>{
                    const color = colors[idx%colors.length];
                    const data = Array.from({length:24}, (_,h)=> bySpider[name][h]||0);
                    datasets.push({ label:name, data, borderColor:color, backgroundColor:`${color}20`, borderWidth:1, fill:false, tension:0.1, pointRadius:0 });
                });
            } else {
                datasets = [{ label:'无数据', data:Array.from({length:24}, ()=>0), borderColor:'#cbd5e1', backgroundColor:'#e2e8f0', borderWidth:1, fill:false, tension:0.1, pointRadius:0 }];
            }
            if (window.spiderHeatLine && typeof window.spiderHeatLine.destroy==='function') window.spiderHeatLine.destroy();
            window.spiderHeatLine = new Chart(ctx, { type:'line', data:{ labels:hours, datasets }, options:{ responsive:true, maintainAspectRatio:false, scales:{ y:{ beginAtZero:true, ticks:{ stepSize:1 } } } } });
        } catch(e){ console.error('初始化热力图失败', e); }
    }

    // 来源占比（无数据渲染 0 占位的环形图）
    function initSpiderSourcesChart(rows){
        const canvas = document.getElementById('spider-sources-premium');
        if (!canvas) return;
        try {
            const ctx = canvas.getContext('2d');
            let labels = [], values = [];
            if (rows && rows.length){
                labels = rows.map(r=> r.spider_name || '未知');
                values = rows.map(r=> parseInt(r.cnt||0,10));
            } else { labels=['无数据']; values=[0]; }
            if (window.spiderSourcesChart && typeof window.spiderSourcesChart.destroy==='function') window.spiderSourcesChart.destroy();
            window.spiderSourcesChart = new Chart(ctx, { type:'doughnut', data:{ labels, datasets:[{ data:values, backgroundColor:['#60a5fa','#34d399','#fbbf24','#f87171','#a78bfa','#22d3ee'] }] }, options:{ responsive:true, maintainAspectRatio:false, cutout:'70%' } });
        } catch(e){ console.error('初始化来源占比失败', e); }
    }

    // 页面加载完成后初始化图表
    if ($('#spider-trend-chart').length > 0) {
        loadSpiderChartData();
    } else {
        console.log('蜘蛛趋势图表元素不存在，跳过初始化');
    }

    // 注意：以下图表（spider-activity-chart, paths-pie-chart, spider-heatmap）需要额外的JavaScript初始化逻辑
    // 请根据需求添加相应的Chart.js配置
});
</script>